package me.jiatao.datastore

import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.SharedPreferencesMigration
import androidx.datastore.preferences.core.*
import androidx.datastore.preferences.preferencesDataStore
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import java.io.IOException

val Context.dataStore: DataStore<Preferences>
        by preferencesDataStore(
            name = "DataStore",
            produceMigrations = { context ->
                listOf(
                    SharedPreferencesMigration(
                        context = context,
                        sharedPreferencesName = "Preferences"
                    )
                )
            }
        )

class MainActivity : AppCompatActivity() {

    private val dataStore: DataStore<Preferences> by lazy { application.dataStore }
    private val name = stringPreferencesKey("name")
    private val age = intPreferencesKey("age")
    private val sex = booleanPreferencesKey("sex")


//    private suspend fun incrementCounter() {
//        dataStore.edit { settings ->
//            val currentCounterValue = settings[EXAMPLE_COUNTER] ?: 0
//            settings[EXAMPLE_COUNTER] = currentCounterValue + 1
//        }
//    }

    private fun readName(): Flow<String> {
        return dataStore.data
            .catch {
                // 当读取数据遇到错误时，如果是 `IOException` 异常，发送一个 emptyPreferences 来重新使用
                // 但是如果是其他的异常，最好将它抛出去，不要隐藏问题
                if (it is IOException) {
                    it.printStackTrace()
                    emit(emptyPreferences())
                } else {
                    throw it
                }
            }
            .map { preferences ->
                preferences[name] ?: ""
            }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


//        val sp = getSharedPreferences("Preferences", Context.MODE_PRIVATE)
//        sp.edit {
//            putString("name", "xiao ming")
//            putInt("age", 20)
//            putBoolean("sex", true)
//            apply()
//        }


        lifecycleScope.launch {
//            delay(3000)
//
//            launch {
//                (1..8).forEach { _ ->
//                    delay(200)
//                    incrementCounter()
//                }
//            }
//
//
            launch {
                readName().collect {
                    println("collect--->$it")
                }

                println("after collect")
            }
        }
    }
}